package cn.zwx.learn.mybatis.example.croe.binding;

import cn.zwx.learn.mybatis.example.croe.session.DefaultSqlSession;
import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * mapper 代理类
 * @author zhangwenxue
 * @date 2022/5/7 22:33
*/
@AllArgsConstructor
public class MapperProxy implements InvocationHandler {

    private DefaultSqlSession sqlSession;

    private Class object;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String mapperInterface = method.getDeclaringClass().getName();
        String methodName = method.getName();
        String statementId = mapperInterface + "." + methodName;
        // 如果根据接口类型+方法名能找到映射的SQL，则执行SQL
        if (sqlSession.getConfiguration().hasStatement(statementId)) {
            return sqlSession.selectList(statementId, args, object);
        }
        // 否则直接执行被代理对象的原方法
        return method.invoke(proxy, args);
    }
}
